"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const DBConnectTool_1 = __importDefault(require("../../../com/DBTool/DBConnectTool"));
const compressible_1 = __importDefault(require("../../FSTool/compressible"));
const zlibPromise_1 = __importDefault(require("../../FSTool/zlibPromise"));
async function saveListToDB(DBName, fileInfo, needCompress = false) {
    if (!fileInfo.length) {
        return true;
    }
    let fileInfoSqlSum = 'INSERT OR IGNORE INTO file_info  (file_name, file_path, file_zip, file_size, file_md5) VALUES ';
    let fileDataSqlSum = 'INSERT OR IGNORE INTO file_data (file_md5, file_data) VALUES ';
    const startCompressTime = new Date().getTime();
    for (let i = 0; i < fileInfo.length; i++) {
        const fileItem = fileInfo[i];
        if (!fileItem.buffer || !fileItem.relativePath) {
            continue;
        }
        let buffer = fileItem.buffer;
        let compressType = fileItem.file_zip || '';
        const relativePath = fileItem.relativePath;
        const md5 = fileItem.md5 || require('crypto').createHash('md5').update(buffer).digest('hex');
        const size = fileItem.file_size || buffer.length;
        const fileName = fileInfo[i].fileName || path_1.default.basename(fileItem.relativePath);
        let file_path = path_1.default.dirname(fileItem.relativePath);
        file_path = file_path === '\\' ? '\\' : file_path + '\\';
        file_path = file_path.replaceAll('/', '\\');
        if (needCompress && buffer && (0, compressible_1.default)(relativePath) && !fileItem.file_zip) {
            buffer = await zlibPromise_1.default.zip(buffer);
            compressType = 'gzip';
        }
        fileInfoSqlSum += `('${fileName}', '${file_path}', '${compressType}', ${size}, '${md5}'),`;
        fileDataSqlSum += `('${md5}', X'${buffer.toString('hex')}'),`;
    }
    const endCompressTime = new Date().getTime();
    try {
        const startSaveTime = new Date().getTime();
        const dbTool = await DBConnectTool_1.default.openDB(DBName);
        const { changes: changesInfo } = await dbTool.sqlite3Promise.insertData(fileInfoSqlSum.substring(0, fileInfoSqlSum.length - 1), []);
        const { changes: changesData } = await dbTool.sqlite3Promise.insertData(fileDataSqlSum.substring(0, fileDataSqlSum.length - 1), []);
        const endSaveTime = new Date().getTime();
        return {
            changesInfo,
            changesData,
            compressTime: endCompressTime - startCompressTime,
            saveTime: endSaveTime - startSaveTime
        };
    }
    catch (e) {
        console.log(e);
        return false;
    }
}
exports.default = saveListToDB;
